import {connect} from "react-redux";
import {fetchUser, toggleMenu, setDefaultUser} from "../actions";
import Left from "../components/left";
import Collapse from "../components/Collapse";
import Fetch from "../libs/fetch";
import {URL} from "../libs/Url";

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {height: window.innerHeight, open: false};
        this._handleResize = this._handleResize.bind(this);
    }

    componentDidMount() {
        window.addEventListener('resize', this._handleResize);
    }

    componentWillMount() {
        const {dispatch} = this.props;
        dispatch(fetchUser()); //获取登录用户信息
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this._handleResize);
    }

    componentWillReceiveProps() {
    }

    _handleResize() {
        this.setState(Object.assign({}, this.state, {height: window.innerHeight}));
    }

    render() {
        const {dispatch, user, collapse, menuItem} = this.props;
        return (
            <div>
                <div className={'main-container ' + (collapse ? 'collapsed-nav' : '')}>
                    <div className="left-menu fl" style={{
                        height: this.state.height,
                    }}>
                        <Left user={user} selected={menuItem}/>
                    </div>
                    <div className="main"
                         style={{height: this.state.height}}
                    >
                        <Collapse
                            onAddClick={text => {
                                dispatch(toggleMenu(text))
                            }}
                            onlogout={()=> {

                                Fetch(URL.Get_LOGOUT)
                                    .then(res=> {
                                        dispatch(setDefaultUser({}));
                                    })
                                    .catch(e=> {
                                        console.log(e)
                                    })
                            }}
                            user={user}
                        />
                        <div className="content-ctner">
                            {this.props.children }
                        </div>
                    </div>

                </div>
            </div>
        )
    }
}

// Which props do we want to inject, given the global state?
// Note: use https://github.com/faassen/reselect for better performance.
function select(state) {
    return {
        collapse: state.toggle.collapse,
        menuItem: state.selected.menuItem,
        user: state.user.user
    }
}

// 包装 component ，注入 dispatch 和 state 到其默认的 connect(select)(App) 中；
export default connect(select)(App)